<?php

namespace app\shop\model\goods;

use app\shop\exception\FailException;
use app\shop\model\BaseModel;
use app\shop\model\delivery\DeliveryTemplateModel;
use think\Model;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasOneThrough;

class GoodsSkuModel extends BaseModel
{
    use SoftDelete;

    /**
     * @var string
     */
    protected $name = 'shop_goods_sku';

    /**
     * 商品关联
     * @return BelongsTo
     */
    public function goods(): BelongsTo
    {
        return $this->belongsTo(GoodsModel::class, 'goods_id', 'id');
    }

    /**
     * SKU模板关联
     * @return HasOneThrough
     */
    public function template(): HasOneThrough
    {
        return $this->hasOneThrough(
            DeliveryTemplateModel::class,
            GoodsModel::class,
            'id',
            'id',
            'goods_id',
            'delivery_template_id'
        );
    }

    /**
     * 获取器：规格描述
     * @param $value
     * @param $data
     * @return string
     * @noinspection PhpUnusedParameterInspection
     * @noinspection PhpUnusedLocalVariableInspection
     */
    public function getSpecTextAttr($value, $data): string
    {
        if (empty($data['spec'])) {
            return '';
        }

        $specs = explode(';', $data['spec']);

        $spec = array_map(function ($item) {
            list($name, $value) = explode(':', $item);
            return $value;
        }, array_filter($specs));

        return implode('，', $spec);
    }

    /**
     * 通过ID获取sku信息
     * @param int $skuId
     * @return GoodsSkuModel|array|mixed|Model
     * @throws FailException
     * @noinspection PhpUnused
     */
    public function getInfoById(int $skuId): mixed
    {
        $skuInfo = $this->where(['id' => $skuId])->findOrEmpty();
        if ($skuInfo->isEmpty()) {
            throw new FailException('商品规格已下架');
        }

        if ($this->goods->isEmpty() || $this->goods->status != 1) {
            throw new FailException("商品{$this->goods->name}已下架");
        }

        return $skuInfo;
    }

    /**
     * 获取器：商品名称
     * @return string
     * @noinspection PhpMissingReturnTypeInspection
     */
    public function getGoodsNameAttr()
    {
        return $this->goods->name ?? '';
    }

    /**
     * 获取器：商品状态
     * @return int
     * @noinspection PhpMissingReturnTypeInspection
     */
    public function getGoodsStatusAttr()
    {
        return $this->goods->status ?? 0;
    }
}
